package com.MediaVaultTest;

import java.io.IOException;
import java.util.LinkedList;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class deleteAll extends HttpServlet {
    private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();

public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws IOException {
	//Setup factories
	 UserService userService = UserServiceFactory.getUserService();
	 User user = userService.getCurrentUser();
	 	
	 //Check user loged in 
	 if(user!=null){
    	String email =  user.getEmail();
    	PersistenceManager pm = PMF.get().getPersistenceManager();
		 UserStore userStore = null;
		 Key key = KeyFactory.createKey(UserStore.class.getSimpleName(), email);
		 try { 
			 //Get the user store and create media file
			 userStore = pm.getObjectById(UserStore.class, key);
			 int size = userStore.getSizeOfMedia();
			 //Delete each media file
			 for(int i = size-1; i >= 0 ; i--){
				 //Delete the cover if any
				 Media media = userStore.getIndMedia(i);
			     if(media.getCover()!=null){
			        blobstoreService.delete(media.getCover());
			     }
			     //delete all formats and stop persistance of formats
			    int numFormats = media.getNumFormats();
			    LinkedList<Format> formatList = media.getFormatList();
			    for (int x = numFormats-1; x >= 0; x--){
			    	Format format = formatList.get(x);
			    	blobstoreService.delete(format.getBlobKey());
			    	pm.deletePersistent(format);
			    }
			     //stop media persistance
			     userStore.removeMediaFile(media);
			     pm.deletePersistent(media);
			 }
		 } finally {
			 //In python i would type pass here
		 }
		userStore.setmbStorage(0);
        pm.close();
        res.sendRedirect("index.jsp");
    }
}
}